package com.edais.service.imp.gift;

import com.edais.domain.User;
import com.edais.domain.gift.GiftPackageGift;
import com.edais.domain.gift.GiftPackageOrder;
import com.edais.persistence.gift.GiftPackageOrderMapper;
import com.edais.service.GiftPackageExchangeFunction;
import com.edais.service.UserService;
import com.edais.service.gift.GiftPackageGiftService;
import com.edais.service.imp.GiftExchangeFunctionInvoke;
import com.edais.util.CommonUtil;
import com.edais.util.Consts;
import com.edais.util.DateUtil;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 福利礼包兑换
 * Created by haoyx on 2016/11/17.
 */
@Service("welfareExchangeImpl")
public class WelfareExchangeImpl implements GiftPackageExchangeFunction {

    private static final Logger logger = Logger.getLogger(WelfareExchangeImpl.class);

    @Autowired
    private UserService userService;

    @Autowired
    private GiftPackageGiftService giftPackageGiftService;

    @Autowired
    private GiftExchangeFunctionInvoke invoke;

    @Autowired
    private GiftPackageOrderMapper packageOrderMapper;

    @Override
    @Transactional(propagation= Propagation.REQUIRED,rollbackFor=Exception.class,readOnly=false)
    public Map<String,String> apply(Map<String,Object> params) throws Exception {

        Map<String, String> resMap = new HashMap<String, String>();
        String error = validParams(params);
        if(!StringUtils.isEmpty(error)){
            logger.info(error);
            error = CommonUtil.setResultStringCn(new HashMap<String, Object>(), Consts.ERROR_CODE,
                    Consts.ErrorMsg.MSG00001,error);
            resMap.put("error",error);
            return resMap;
        }


        //参数列表
        Long userId = Long.parseLong(params.get("userId").toString());
        String mobile = String.valueOf(params.get("mobile"));
        GiftPackageOrder packageOrder = (GiftPackageOrder)params.get("packageOrder");

        final String logInfo = "兑换福利礼包" + packageOrder.getId() + userId + "-";

        //验证用户合法性
        User user = this.userService.selectUser(userId,mobile);
        if(null == user){
            logger.info(logInfo+"查询不到此用户");
            error = CommonUtil.setResultStringCn(new HashMap<String, Object>(),Consts.ERROR_CODE,
                    Consts.ErrorMsg.MSG00001,"查询不到此用户");
            resMap.put("error",error);
            return resMap;
        }

        Date nowDate = this.userService.getSysdate();

        //验证状态
        if (!GiftPackageOrder.STATUS_INIT.equals(packageOrder.getStatus())) {
            logger.info(logInfo+"状态异常");
            error = CommonUtil.setResultStringCn(new HashMap<String, Object>(), Consts.ERROR_CODE,
                    Consts.ErrorMsg.MSG00001, "状态异常");
            resMap.put("error", error);
            return resMap;
        }

        //验证开始兑换时间
        Date startDate = packageOrder.getStartDate();
        
        if (nowDate.before(startDate)) {
        	int day= DateUtil.daysBetween(nowDate,startDate);  
            logger.info(logInfo+"未到兑换时间");
            error = CommonUtil.setResultStringCn(new HashMap<String, Object>(), Consts.ERROR_CODE,
                    Consts.ErrorMsg.MSG00001, "还剩"+day +"天可以兑换");
            resMap.put("error", error);
            return resMap;
        }

        //验证兑换结束数据
        Date endDate = packageOrder.getEndDate();
        if (nowDate.after(endDate)) {
            logger.info(logInfo+"礼包已过期");
            error = CommonUtil.setResultStringCn(new HashMap<String, Object>(), Consts.ERROR_CODE,
                    Consts.ErrorMsg.MSG00001, "礼包已过期");
            resMap.put("error", error);
            return resMap;
        }

        logger.info(logInfo+"开始");

        //更新订单状态--锁
        packageOrder.setStatus(GiftPackageOrder.STATUS_SUCCESS);
        packageOrder.setUpdateTime(nowDate);
        packageOrder.setUpdatePer("javaservice");
        packageOrder.setExchangeDate(nowDate);
        
		int updateNum = this.packageOrderMapper.updateOrderStatus(packageOrder);
		if (updateNum == 0) {
			logger.info(logInfo + "礼包已兑换");
			error = CommonUtil.setResultStringCn(new HashMap<String, Object>(), Consts.ERROR_CODE,
					Consts.ErrorMsg.MSG00001, "礼包已兑换");
			resMap.put("error", error);
			return resMap;
		}
		
        //查询礼品订单
        Map<String,Object> giftParams = new HashMap<String, Object>();
        giftParams.put("packageId",packageOrder.getPackageId());
        giftParams.put("userId",userId);
        giftParams.put("mobile",mobile);
        List<GiftPackageGift> giftList = giftPackageGiftService.selectGiftPackageGifts(giftParams);
        if(null != giftList && !giftList.isEmpty()){
            Map<String,Object> invokeParams = new HashMap<String,Object>();
            invokeParams.put("userId",userId);
            invokeParams.put("mobile",mobile);
            invokeParams.put("packageOrderId",packageOrder.getId());
            for(GiftPackageGift gift : giftList){
                if(null == gift)
                    continue;
                if(null == gift.getAmount()){//为null赠送一次
                    //赠送礼品
                    invoke.apply(gift.getId(),invokeParams);
                    continue;
                }
                //数量为多个的时候循环赠送
                for(int a = 0; a < gift.getAmount();a++){
                    //赠送礼品
                    invoke.apply(gift.getId(),invokeParams);
                }
            }
           
            
        }else{
            logger.info(logInfo+"礼包内不包含礼品");
        }

        logger.info(logInfo+"结束");

        return resMap;
    }

    @Override
    public String validParams(Map params) {
        if(null == params || params.isEmpty())
            return "参数列表不能为空";
        if(!params.containsKey("packageOrder") || null == params.get("packageOrder"))
            return "参数packageOrder不能为空";
        if(!params.containsKey("userId")  || StringUtils.isEmpty(params.get("userId")))
            return "参数userId不能为空";
        if(!params.containsKey("mobile")  || StringUtils.isEmpty(params.get("mobile")))
            return "参数mobile不能为空";
        return null;
    }
}
